package cn.nuomi.shop.api.controller;

import cn.nuomi.shop.api.entity.User;
import cn.nuomi.shop.api.service.UserService;
import cn.nuomi.shop.api.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @date: 2021/4/26 17:27
 * @description:
 */

@WebServlet("/register")
public class RegisterServlet extends BaseServlet{
    private UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //注册验证
        //获取到用户注册输入的用户名
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");
        try {
            //调用业务进行用户注册
            User dbUser = userService.checkRegister(userName,password);
            //注册成功
            HttpSession session = req.getSession();
            session.setAttribute("sessionUser", dbUser);

            //跨域
            resp.setHeader("Access-Control-Allow-Origin", "*");

            //返回用户信息
            successResp(resp, dbUser);
        } catch (RuntimeException e) {
            e.printStackTrace();
            //登录失败，返回错误信息
            errorResp(resp, e.getMessage());
        }
    }
}
